package com.ex.realm;

import com.ex.entity.Account;
import com.ex.service.AccountService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

/**
 * <h1>shiro登录Realm控制</h1>
 *
 * @author longdeng
 * @Date 2019/10/7 19:36
 */
@Slf4j
public class LoginRealm extends AuthorizingRealm {

    @Autowired
    private AccountService accountService;

    /**
     * shiro认证流程
     *
     * @param token {@link AuthenticationToken}
     * @return 返回认证的用户信息 shiro {@link SimpleAuthenticationInfo}
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken t = (UsernamePasswordToken) token;
        Account account = accountService.findByUsername(t.getUsername());
        if (Objects.isNull(account)) {
            log.info("认证失败，不存在该账户 {} ", t.getUsername());
            throw new AuthenticationException("认证失败,不存在该用户");
        }
        // Object principal, Object credentials, String realmName
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                account,                // 账户信息
                account.getPassword(),  // 账户密码
                getName()               // 当前realm名称
        );
        return authenticationInfo;
    }

    /**
     * 我这里的需求主要是对请求的url做拦截
     * 主要将需要拦截的权限信息添加到shiro中
     *
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        Account account = (Account) principals.getPrimaryPrincipal();
        // 通过account信息查询出权限信息
        Set<String> set = new HashSet<>();
        set.add("zhxl1");
        set.add("zhxl2");
        set.add("zhxl3");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(set);
        return info;
    }
}
